<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="pageParams.departments">
        <el-form-item>
          <el-input v-model="queryParams.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" v-on:click="queryBykeyword" round>搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" @click="handleAdd" round>新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageParams.departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <!-- 编号自增长-->
      <el-table-column type="index" width="50" label="序号">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" sortable/>
      <el-table-column prop="sn" label="部门编号" width="120" sortable/>
      <el-table-column prop="dirPath" label="上级部门id" width="120" sortable/>
      <el-table-column label="状态" width="100">
        <template scope="scope">
          <span style="color: #13ce66" v-if="scope.row.state==1">启用</span>
          <span style="color: #e64242"  v-else>禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门经理" width="120" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="120" sortable>
      </el-table-column>

      <el-table-column label="操作" >
        <template scope="scope">
          <el-button style="color: darkblue" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button style="color: #e64242" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="queryParams.pageSize" :total="pageParams.totals" style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">

        <el-form-item label="姓名" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>

        </el-form-item>
        <el-form-item label="部门经理">
          <el-select v-model="saveForm.manager" value-key="id" placeholder="请选择">
            <!--
              el-select - 下拉框
                v-model="saveForm.manager" - 回显数据
                placeholder="请选择" - 提示语
              el-option - 每一个选项
                v-for="emp in managers" - 遍历
                :label="emp.username" - 回显哪一个值：emp对象的username属性
                :value="emp" - 点击保存你要传递到后端的数据
              回显机制：
                v-model="saveForm.manager"
                value-key	作为 value 唯一标识的键名，绑定值为对象类型时必填
                value-key="id" - 因为我们绑定的是一个对象saveForm.manager，对象里面有多个值： id: 324, username: "东邪"
                  使用id作为回显的唯一标识
            -->
            <el-option v-for="emp in managers" :label="emp.username" :value="emp">
              <span style="float: left">{{ emp.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ emp.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent"
                       :options="deptTree"
                       :props="{
                         checkStrictly: true,
                          label: 'name', //级联框显示那个属性的值
                          value: 'id'   //点击提交按钮发送请求的时候传递的参数
                        }"clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
console.log(parent.name)
// import util from '../../common/js/util'
// //import NProgress from 'nprogress'
// import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

export default {
  data() {
    return {
      pageParams:{
        departments:[],
        totals:0
      },
      queryParams:{
        pageSize: 5,
        currentPage:1,
        keyword:''
      },

      //列表忙等框
      listLoading: false,
      //批量删除 - 保存选中的列
      sels: [],//列表选中列
      title:"保存",
      saveFormVisible: false,//编辑界面是否显示
      saveLoading: false,
      saveFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        sn: [
          { required: true, message: '请输入编号', trigger: 'blur' }
        ]
      },
      //编辑界面数据
      saveForm: {
        id: null,
        sn: null,
        name: null,
        state: 1, //默认启用
        manager: null,
        parent: null
      },
      managers:[], //保存所有的经理 - 员工
      deptTree:[] //加载部门树
    }
  },
  methods: {
    //性别显示转换
    formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },
    handleCurrentChange(val) {
      this.queryParams.currentPage = val;
      this.getDepartments();
    },
    queryBykeyword(){
      this.queryParams.currentPage = 1;
      this.getDepartments();
    },
    //获取部门列表
    getDepartments() {
      this.listLoading=true;
      this.$http.post("/department",this.queryParams).then(res=>{
        this.pageParams.totals=res.data.totals;
        this.pageParams.departments = res.data.data;
        this.listLoading=false;
      }).catch(res=>{
        this.$message.error("系统繁忙稍后再试")
      })
    },
    getManagers(){
      this.$http.get("/employee").then(res=>{
        this.managers=res.data;
      }).catch(res=>{
        this.$message.error("查询失败")
      })
    },
    getDeptTree(){
      this.$http.get("/department/deptTree").then(res => {
        this.deptTree = res.data;
      })
          .catch(res => {
            this.$message.error('获取部门树失败,请稍后重试');
          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.delete("/department/"+row.id)
            .then(res=>{
              if (res.data.success){
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.getDepartments();
              }else {
                this.$message({
                  message:res.data.message,
                  type:"error"
                });
              }
            }).catch(res=>{
          res.$message.error("系统错误");
        });
      }).catch(() => {
      });
    },

    //点击添加按钮弹出模态框
    handleAdd: function () {
      this.title = "新增";
      //重置
      this.saveForm = {
        id: null,
        sn: null,
        name: null,
        state: 1, //默认启用
        manager: null,
        parent: null
      };
      //显示模态框
      this.getManagers();
      this.getDeptTree();
      this.saveFormVisible = true;
    },
    //点击修改按钮弹出模态框
    handleEdit: function (index, row) {
      this.title = "编辑";
      //克隆 - 回显
      this.saveForm = Object.assign({}, row);

      //点击修改操作对上级部门的回显做处理
      var dirPath = row.dirPath; //   /2/5/10
      var idArr = dirPath.split("/"); // ["","2","5","10"]
      var arr = [];
      for(var i=1;i<idArr.length-1;i++){
        var id = parseInt(idArr[i]);
        arr[i-1] = id;  //arr[0]=2, arr[1]=5
      }
      this.saveForm.parent = arr;
      //加载所有的经理 - 员工
      this.getManagers();
      //加载部门树：
      this.getDeptTree();
      this.saveFormVisible = true; //显示模态框
    },

    saveSubmit: function () {
      //提交验证 - 只要表单验证不通过都不能提交
      this.$refs.saveForm.validate((valid) => {
        //如果验证通过返回true，返回返回false
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //显示忙等框
            this.saveLoading = true;

            //点击提交将提交的数据 格式转成  对象
            var arr = this.saveForm.parent; //[ 2, 5 ]
            if(arr){
              this.saveForm.parent = {id:arr[arr.length-1]}
            }

            //提交的数据
            var para = Object.assign({}, this.saveForm);

            this.$http.put("/department",para).then(res => {
              this.saveLoading = false;//关闭忙等框
              if(res.data.success){
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                //重置表单
                // this.$refs['saveForm'].resetFields();
                this.saveFormVisible = false; //关闭模态框
                this.getDepartments();
              }else{
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                });
                this.saveFormVisible = false; //关闭模态框
              }
            }).catch(res=>{
              this.$message.error('系统错误,请稍后重试');  //连不上后端代码或404，400
            })
          });
        }
      });
    },
    //新增
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            var para = Object.assign({}, this.addForm);
            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            addDepartment(para).then((res) => {
              this.addLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['addForm'].resetFields();
              this.addFormVisible = false;
              this.getDepartments();
            });
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/department",ids)
            .then(res=>{
              this.listLoading = false;
              if (res.data.success){
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.queryParams.currentPage=1;
                this.getDepartments();
              }else {
                this.$message({
                  message: res.data.message,
                  type: 'error'
                });
              }
            })
      }).catch(() => {
      });
    }
  },
  mounted() {
    this.getDepartments();
  }
}

</script>

<style scoped>

</style>